package operate.rw;


/**
 * 读者线程，继承了Runnable接口。和OSThread类
 *
 * @author zxc
 */
public class Reader extends OSThread implements Runnable {
    private final Semaphore rMutex;
    private final Semaphore rwMutex;
    private final Semaphore wMutex;
    private static int readCount = 0;

    public Reader(Semaphore rMutex, Semaphore wMutex, Semaphore rwMutex, double delay, double persist) {
        super(delay, persist);
        this.rMutex = rMutex;
        this.rwMutex = rwMutex;
        this.wMutex = wMutex;
    }


    /**
     * 读写公平
     */
    public void run() {
        // 线程名
        String name = "Reader thread " + Thread.currentThread().getName();
        try {
            Thread.sleep((long) (super.getDelay() * INTE_PER_SEC));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " sents the reading require !");

        wMutex.p();
        rMutex.p();
        // 只有第一个读者进程需要执行 rwMutex.p()
        if (readCount == 0) rwMutex.p();
        readCount++;
        rMutex.v();
        wMutex.v();

        // 执行读操作
        System.out.println(name + " begins to read file !");
        try {
            Thread.sleep((long) (super.getPersist() * INTE_PER_SEC));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        rMutex.p();
        readCount--;
        if (readCount == 0) rwMutex.v();
        rMutex.v();
        System.out.println(name + " finished reading file !");
    }
}